package com.dmzapp.api.servlet;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dmzapp.api.cache.local.LocalCache;
import com.dmzapp.api.util.PropsUtils;

/**
 * Servlet implementation class for Servlet: DMZSerlvet
 */
public abstract class DMZSerlvet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    static final long serialVersionUID = 1L;

    /*
     * (non-Java-doc)
     * 
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public DMZSerlvet() {
        super();
    }

    protected abstract void handle(HttpServletRequest request, HttpServletResponse response);

    private void commonoperation(HttpServletRequest request, HttpServletResponse response) {

        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //Http 1.0 header
        response.setDateHeader("Expires", 0);
        response.addHeader("Pragma", "no-cache");
        //Http 1.1 header
        response.setHeader("Cache-Control", "no-cache");
        
    }

    /*
     * (non-Java-doc)
     * 
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
     *      HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");
        
        commonoperation(request, response);
        
        handle(request, response);

    }

    /*
     * (non-Java-doc)
     * 
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
     *      HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        response.setCharacterEncoding("UTF-8");
        
        commonoperation(request, response);
        
        handle(request, response);

    }
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        String dir = getClass().getClassLoader().getResource("/").getPath();
        System.out.println(dir);
        try {
            PropsUtils.load2SystemProperties(new File(dir + "env.properties"));
        } catch (IOException e) {
            
            throw new ServletException(e);
        }
        LocalCache.getInstance();
        super.init(config);
    }
}